/**
 * @Author: ls <ls-mac>
 * @Date:   2019-08-13 23:16:25
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-07-20 00:54:28
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Popover,
  Popconfirm,
  TimePicker,
  Table,
  Modal,
  message,
  Badge,
  Divider,
  Upload,
} from 'antd';
import moment from 'moment';
import SimpleTable from 'components/SimpleTable';
import styles from './enterprise.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const { RangePicker } = DatePicker;

const { Search } = Input;

const { Option } = Select;

const FormItem = Form.Item;

const CreateForm = Form.create()(prop => {
  const {
    state,
    form,
    props,
    handleCancel,
    renderOptionsH,
    renderOptionsS,
    renderOptionsP,
    renderOptionsC,
    renderOptionsI,
    onChangeH,
    onChangeP,
    onChangeC,
    onChangeI,
    onSelect,
  } = prop;
  const { modalVisible, type, record, result } = state;
  const { getFieldDecorator } = form;
  const { dispatch } = props;

  const detailInfo = type === 'edit' ? record : {};

  let storeIdSelected = '';

  const changeStoreId = e => {
    const {
      dict: { storeList },
    } = props;
    const { checked } = e.target;

    if (checked) {
      const newList = storeIdSelected
        ? storeIdSelected
        : storeList.map(v => {
            return v.name;
          });
      form.setFieldsValue({ storeId: newList });
    } else {
      form.setFieldsValue({ storeId: [] });
    }
  };

  const changeContractId = e => {
    const { checked } = e.target;
    const {
      contractList: { list },
    } = props;

    if (checked) {
      const newList = list.map(v => {
        return v.id;
      });
      form.setFieldsValue({ contractId: newList });
    } else {
      form.setFieldsValue({ contractId: [] });
    }
  };

  const handleOk = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return false;
      const params = {
        beginDate: moment(fieldsValue.storeUnavailableTimeList[0]).format('YYYY-MM-DD'),
        endDate: moment(fieldsValue.storeUnavailableTimeList[1]).format('YYYY-MM-DD'),
      };

      let url = '';

      if (type === 'add') {
        params.contractId = fieldsValue.contractId;
        params.shopId = fieldsValue.storeId;
        url = 'storeUnavailableTimeList/dictStoreUnavailableTimeAdd';
      } else {
        params.id = record.id;
        url = 'storeUnavailableTimeList/dictStoreUnavailableTimeEdit';
      }

      // if (type === 'add') {
      //   const { storeId, storeUnavailableTimeList } = fieldsValue;
      //
      //   const beginDate = moment(fieldsValue.storeUnavailableTimeList[0]).format('YYYY-MM-DD');
      //   const endDate = moment(fieldsValue.storeUnavailableTimeList[1]).format('YYYY-MM-DD');
      //
      //   const newlist = storeId.map(v => {
      //     return { beginDate, endDate, storeId: v };
      //   });
      //
      //   params.storeUnavailableTimeList = newlist;
      //
      //   if (record.id) {
      //     params.id = record.id;
      //   }
      // } else {
      //   params.contractId = record.contractId;
      //   const beginDate = moment(fieldsValue.storeUnavailableTimeList[0]).format('YYYY-MM-DD');
      //   const endDate = moment(fieldsValue.storeUnavailableTimeList[1]).format('YYYY-MM-DD');
      //   let a = [];
      //   a.push({
      //     beginDate,
      //     endDate,
      //     id: record.id,
      //     storeId: record.storeId,
      //   });
      //   params.storeUnavailableTimeList = a;
      // }
      dispatch({
        type: url,
        payload: params,
        callback: res => {
          if (res.success) {
            message.success(
              type === 'add' ? '新增门店不可预约时间成功' : '修改门店不可预约时间成功'
            );
            handleCancel();
          } else {
            message.info(res.errorDesc);
          }
        },
      });
    });
  };

  return (
    <Modal
      title={type === 'add' ? '新增门店不可预约时间' : '修改门店不可预约时间'}
      visible={modalVisible}
      className={styles.unavailableTimeListModal}
      onOk={() => handleOk()}
      onCancel={() => handleCancel()}
      okText="提交"
      width="540px"
      destroyOnClose
    >
      {type === 'add' ? (
        <div>
          <Row gutter={{ lg: 24 }}>
            <Col md={8} sm={24}>
              <span>选择省份：</span>
              <Select
                showSearch
                allowClear={true}
                onSelect={onChangeP}
                placeholder="请选择"
                style={{ width: 80 }}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {renderOptionsP()}
              </Select>
            </Col>
            <Col md={8} sm={24}>
              <span>选择城市：</span>
              <Select
                showSearch
                allowClear
                onSelect={onChangeC}
                placeholder="请选择"
                style={{ width: 80 }}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {renderOptionsC()}
              </Select>
            </Col>
            <Col md={8} sm={24}>
              <span>选择机构：</span>
              <Select
                showSearch
                allowClear
                onSelect={onChangeI}
                placeholder="请选择"
                style={{ width: 80 }}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {renderOptionsI()}
              </Select>
            </Col>
          </Row>
          <Divider />
          <Form layout="inline">
            <Row gutter={{ lg: 24 }}>
              <Col md={24} sm={24}>
                <FormItem label="合同名称&#12288;&#12288;">
                  {getFieldDecorator('contractId', {
                    rules: [{ required: true, message: '请选择合同名称' }],
                  })(
                    <Select
                      placeholder="请选择合同"
                      style={{ width: 300 }}
                      mode="multiple"
                      maxTagCount={50}
                      showSearch={false}
                      dropdownRender={menu => (
                        <div
                          onMouseDown={e => {
                            e.preventDefault();
                            return false;
                          }}
                        >
                          {menu}
                          <Divider style={{ margin: '2px 0' }} />
                          <div style={{ padding: '4px 8px 8px 8px' }}>
                            <Checkbox onChange={changeContractId}>全选</Checkbox>
                          </div>
                        </div>
                      )}
                    >
                      {renderOptionsH()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ lg: 24 }}>
              <Col md={24} sm={24}>
                <FormItem label="门店名称&#12288;&#12288;">
                  {getFieldDecorator('storeId', {
                    initialValue: detailInfo?.storeId,
                    rules: [{ required: true, message: '请选择门店' }],
                  })(
                    <Select
                      placeholder="请选择门店名称"
                      style={{ width: 300 }}
                      mode="multiple"
                      maxTagCount={50}
                      showSearch={false}
                      dropdownRender={menu => (
                        <div
                          onMouseDown={e => {
                            e.preventDefault();
                            return false;
                          }}
                        >
                          {menu}
                          <Divider style={{ margin: '2px 0' }} />
                          <div style={{ padding: '4px 8px 8px 8px', cursor: 'pointer' }}>
                            <Checkbox onChange={changeStoreId}>全选</Checkbox>
                          </div>
                        </div>
                      )}
                    >
                      {renderOptionsS()}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={{ lg: 24 }}>
              <Col md={24} sm={24}>
                <FormItem label="不可预约时间">
                  {getFieldDecorator('storeUnavailableTimeList', {
                    rules: [{ required: true, message: '请选择不可预约时间' }],
                  })(<RangePicker style={{ width: 300 }} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>{' '}
        </div>
      ) : (
        <Form layout="inline">
          <Row gutter={{ lg: 24 }}>
            <Col md={24} sm={24}>
              <FormItem label="不可预约时间">
                {getFieldDecorator('storeUnavailableTimeList', {
                  initialValue: [moment(detailInfo?.beginDate), moment(detailInfo?.endDate)],
                  rules: [{ required: true, message: '请选择不可预约时间' }],
                })(<RangePicker style={{ width: 300 }} />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      )}
    </Modal>
  );
});

@connect(
  ({
    storeUnavailableTimeList,
    dict,
    contractList,
    companyStorePage,
    institutionList,
    loading,
  }) => ({
    storeUnavailableTimeList,
    dict,
    contractList,
    companyStorePage,
    institutionList,
    loading: loading.models.storeUnavailableTimeList,
  })
)
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    type: 'add',
    record: {},
    result: [],
    current: 1,
    pageSize: 10,
    selectedRows: [],
    flag: 1,
  };

  componentDidMount() {
    const { dispatch, form } = this.props;
    // const { current, pageSize } = this.state;
    const pagination = sessionStorage.getItem('unavailableTimeList-pagination')
      ? JSON.parse(sessionStorage.getItem('unavailableTimeList-pagination'))
      : '';
    const fieldsValue = sessionStorage.getItem('unavailableTimeList-fieldsValue')
      ? JSON.parse(sessionStorage.getItem('unavailableTimeList-fieldsValue'))
      : {};

    form.setFieldsValue(fieldsValue);

    dispatch({
      type: 'storeUnavailableTimeList/fetch',
      payload: {
        cityId: '',
        contractId: '',
        institutionId: '',
        storeName: '',
        pageIndex: pagination ? pagination.current : '1',
        pageSize: pagination ? pagination.pageSize : '10',
        ...fieldsValue,
      },
    });

    // 查询省份
    dispatch({
      type: 'dict/dictProvinceList',
      payload: {},
    });

    // 查询城市
    dispatch({
      type: 'dict/dictCityList',
      payload: {},
    });

    dispatch({
      type: 'companyStorePage/companyList',
      payload: {
        name: '',
      },
      callback: res => {
        const newList = res.data.map(v => {
          return (
            <Option key={v.i} value={v.id}>
              {v.name}
            </Option>
          );
        });
        this.setState({
          result: newList,
        });
      },
    });

    // 查询合同
    dispatch({
      type: 'contractList/getList',
      payload: {},
    });

    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: {},
    });

    // 适用机构
    dispatch({
      type: 'institutionList/dictInstitutionList',
      payload: {},
    });
  }

  onChangeP = v => {
    // 查询城市
    const { dispatch } = this.props;
    const { cityId, institutionId } = this.state;
    this.setState({
      provinceId: v,
    });
    dispatch({
      type: 'dict/dictCityList',
      payload: { provinceId: v, cityId, institutionId },
    });
  };

  onChangeC = v => {
    // 查询门店
    const { dispatch } = this.props;
    const { provinceId, institutionId } = this.state;
    this.setState({
      cityId: v,
    });
    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: { cityId: v, institutionId, provinceId },
    });
  };

  onChangeI = v => {
    // 查询门店
    const { dispatch } = this.props;
    const { cityId, provinceId } = this.state;

    this.setState({
      institutionId: v,
    });
    // 查询门店
    dispatch({
      type: 'dict/dictStoreList',
      payload: { institutionId: v, cityId, provinceId },
    });
  };

  onChangeH = () => {};

  onSelect = v => {
    const { dispatch } = this.props;
    // 查询合同
    dispatch({
      type: 'contractList/getList',
      payload: { companyId: v },
    });
  };

  reColumns = () => {
    const that = this;

    return [
      {
        title: '合同标题',
        dataIndex: 'contractTitle',
      },
      {
        title: '体检机构',
        dataIndex: 'institutionName',
      },
      {
        title: '省份',
        dataIndex: 'provinceName',
      },
      {
        title: '城市',
        dataIndex: 'cityName',
      },
      {
        title: '门店名称',
        dataIndex: 'storeName',
      },
      {
        title: '不可预约时间',
        dataIndex: '',
        render: (v, r) => (
          <span>
            {r.beginDate}~{r.endDate}
          </span>
        ),
      },
      {
        title: '操作',
        render: (val, record) => (
          <div>
            <a onClick={() => that.handleEdit(record)}>修改</a>
            <br />
            <a onClick={() => that.handleDelete(record)}>删除</a>
          </div>
        ),
      },
    ];
  };

  // 分页
  handleStandardTableChange = pagination => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        ...fieldsValue,
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
      };

      // this.setState({
      //   current: pagination.current,
      //   pageSize: pagination.pageSize,
      // });

      dispatch({
        type: 'storeUnavailableTimeList/fetch',
        payload: params,
      });

      sessionStorage.setItem('unavailableTimeList-pagination', `${JSON.stringify(pagination)}`);
    });
  };

  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    sessionStorage.setItem('unavailableTimeList-pagination', '');
    sessionStorage.setItem('unavailableTimeList-fieldsValue', '');
    dispatch({
      type: 'storeUnavailableTimeList/fetch',
      payload: {
        cityId: '',
        contractId: '',
        institutionId: '',
        storeName: '',
        pageIndex: '1',
        pageSize: '10',
      },
    });
  };

  handleSearch = e => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const params = {
        pageIndex: 0,
        pageSize: 10,
        ...fieldsValue,
      };

      sessionStorage.setItem('unavailableTimeList-fieldsValue', `${JSON.stringify(fieldsValue)}`);
      sessionStorage.setItem(
        'unavailableTimeList-pagination',
        `${JSON.stringify({ current: 1, pageSize: 10 })}`
      );

      dispatch({
        type: 'storeUnavailableTimeList/fetch',
        payload: params,
      });
    });
  };

  // 刷新
  handleRefresh = () => {
    window.location.reload(true);

    // const { current, pageSize } = this.state;
    // const { dispatch, form } = this.props;
    // form.validateFields((err, fieldsValue) => {
    //   if (err) return;
    //
    //   const params = {
    //     pageIndex: current,
    //     pageSize: pageSize,
    //     ...fieldsValue,
    //   };
    //
    //   dispatch({
    //     type: 'storeUnavailableTimeList/fetch',
    //     payload: params,
    //   });
    // });
  };

  handleEdit = record => {
    const { dispatch } = this.props;
    this.setState({
      type: 'edit',
      modalVisible: true,
      record,
    });
  };

  handleCancel = () => {
    this.setState({
      modalVisible: false,
    });
    this.handleRefresh();
  };

  handleAdd = () => {
    this.setState({
      record: '',
      type: 'add',
      modalVisible: true,
    });
  };

  handleDelete = record => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    const id = record === 'all' ? selectedRows : [record.id];
    dispatch({
      type: 'storeUnavailableTimeList/dictStoreUnavailableTimeDelete',
      payload: { id },
      callback: res => {
        if (res.success) {
          message.success('删除成功');
        } else {
          message.info(res.errorDesc);
        }
        this.handleRefresh();
      },
    });
  };

  handleSelectRows = rows => {
    const id = rows.map(v => {
      return v.id;
    });

    this.setState({
      selectedRows: id,
    });
  };

  renderOptionsP = () => {
    const {
      dict: { provinceList },
    } = this.props;

    const options = provinceList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    options.unshift(
      <Option key="" value="">
        全部
      </Option>
    );

    return options;
  };

  renderOptionsC = () => {
    const {
      dict: { cityList },
    } = this.props;
    const options = cityList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    options.unshift(
      <Option key="" value="">
        全部
      </Option>
    );
    return options;
  };

  renderOptionsI = () => {
    const {
      institutionList: { dictInstitutionList },
    } = this.props;
    const options = dictInstitutionList.map(v => (
      <Option key={v.id} value={v.id}>
        {v.name}
      </Option>
    ));
    options.unshift(
      <Option key="" value="">
        全部
      </Option>
    );
    return options;
  };

  renderOptionsH = () => {
    const {
      contractList: { list },
    } = this.props;
    const options = list.map(v => (
      <Option value={v.id} key={v.id} label={v.title}>
        {v.title}
      </Option>
    ));

    options.unshift(
      <Option key="0" value="0">
        全部
      </Option>
    );
    return options;
  };

  renderOptionsS = () => {
    const {
      dict: { storeList },
    } = this.props;
    const options = storeList.map(v => (
      <Option value={v.id} key={v.id} label={v.name}>
        {v.name}
      </Option>
    ));
    return options;
  };

  renderSearchForm = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="合同名称">
              {getFieldDecorator('contractName')(<Input placeholder="请输入合同名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="城市名称">
              {getFieldDecorator('cityName')(<Input placeholder="请输入城市名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="机构名称">
              {getFieldDecorator('institutionName')(<Input placeholder="请输入机构名称" />)}
            </FormItem>
          </Col>
        </Row>
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="门店名称">
              {getFieldDecorator('storeName')(<Input placeholder="请输入门店名称" />)}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <div
              style={{
                overflow: 'hidden',
                height: '40px',
                lineHeight: '40px',
              }}
            >
              <span
                style={{
                  float: 'right',
                }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button
                  style={{
                    marginLeft: 8,
                  }}
                  onClick={this.handleFormReset}
                >
                  重置
                </Button>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const columns = this.reColumns();
    const {
      storeUnavailableTimeList: { data },
      loading,
    } = this.props;

    const selectedRows = this.state;
    return (
      <PageHeaderLayout>
        <Card bordered={false} style={{ paddingBottom: '20px' }}>
          <div>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
            <div>
              <Button type="primary" icon="plus" onClick={this.handleAdd}>
                新增
              </Button>
              <Button
                style={{ marginLeft: 20 }}
                type="primary"
                icon="delete"
                onClick={() => this.handleDelete('all')}
              >
                删除
              </Button>
            </div>
            <SimpleTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="id"
            />
          </div>
        </Card>
        <CreateForm {...this} />
      </PageHeaderLayout>
    );
  }
}
